#导入必要的库和模块
import gradio as gr
import pickle
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
from PIL import Image

#加载保存的KNN模型，这样我们可以使用预训练的模型进行预测
try:
    with open('best_knn.pkl', 'rb') as file:
        knn = pickle.load(file)
except FileNotFoundError:
    print("无法找到保存的KNN模型文件")
    exit()
except Exception as e:
    print("加载KNN模型时出现错误:", str(e))
    exit()

#定义预测函数，这个函数将用于Gradio接口进行预测
def preprocess(image):
    image = Image.fromarray(image)
    image = image.resize((8, 8)).convert('L')
    image_array = np.array(image)
    flattened_image = image_array.ravel()
    return flattened_image
def predict(image):
    preprocessed_image = preprocess(image)
    predicted_digit = knn.predict([preprocessed_image])[0]
    return str(predicted_digit) 

#创建Gradio接口，这个接口将用于用户输入和显示预测结果
iface = gr.Interface(fn=predict, inputs='sketchpad', outputs='label')

#启动Gradio接口，用户可以通过这个接口进行交互
iface.launch()
